package com.idp.web.test.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ebay.sdk.ApiException;
import com.ebay.sdk.SdkException;
import com.idp.common.base.BaseController;
import com.idp.common.persistence.Page;
import com.idp.common.util.ValidateUtils;
import com.idp.ebay.domain.EBayInfo;
import com.idp.ebay.domain.EBayInfoNeed;
import com.idp.ebay.test.ReturnEBayOrder;
import com.idp.ebay.utils.ExcelFileUtil;
import com.idp.web.system.entity.SysOrg;
import com.idp.web.test.dao.AccountDao;
import com.idp.web.test.dao.DeliverGoodsDao;
import com.idp.web.test.dao.LogisticsDao;
import com.idp.web.test.dao.OrderItemDao;
import com.idp.web.test.dao.OrdertDao;
import com.idp.web.test.dao.PersonDao;
import com.idp.web.test.dao.PlatformDao;
import com.idp.web.test.dao.ProductDao;
import com.idp.web.test.entity.Account;
import com.idp.web.test.entity.DeliverGoods;
import com.idp.web.test.entity.Logistics;
import com.idp.web.test.entity.OrderItem;
import com.idp.web.test.entity.OrderStatus;
import com.idp.web.test.entity.Ordert;
import com.idp.web.test.entity.Person;
import com.idp.web.test.entity.Platform;
import com.idp.web.test.entity.Product;
import com.idp.web.test.entity.Warehouse;
import com.idp.web.test.service.AccountService;
import com.idp.web.test.service.LogisticsService;
import com.idp.web.test.service.OrderStatusService;
import com.idp.web.test.service.OrdertService;
import com.idp.web.test.service.PlatformService;
import com.idp.web.test.service.WarehouseService;

import net.sf.json.JSONObject;

/**
 * 
 * 
 * 
 * <pre>
 * 	历史记录：
 * 	2017-06-02 Amber
 * 	新建文件
 * </pre>
 * 
 * @author
 * 
 *         <pre>
 * SD
 * 	Amber
 * PG
 *	Amber
 * UT
 *
 * MA
 *         </pre>
 * 
 * @version $Rev$
 *
 *          <p/>
 *          $Id$
 *
 */
@Controller
@RequestMapping("/ordert")
public class OrdertController extends BaseController {

	private Logger logger = Logger.getLogger(OrdertController.class);

	@Resource
	private OrdertService ordertService;

	@Resource
	private WarehouseService warehouseService;

	@Resource
	private PlatformService platformService;

	@Resource
	private OrderStatusService orderStatusService;

	@Resource
	private LogisticsService logisticsService;

	@Resource
	private AccountService accountService;

	@Resource
	private OrdertDao ordertDao;

	@Resource
	private ProductDao productDao;

	@Resource
	private PersonDao personDao;

	@Resource
	private OrderItemDao orderItemDao;

	@Resource
	private DeliverGoodsDao deliverGoodsDao;

	@Resource
	private PlatformDao platformDao;

	@Resource
	private LogisticsDao logisticsDao;

	@Resource
	private AccountDao accountDao;

	private List<Ordert> olist;

	public List<Ordert> getOlist() {
		return olist;
	}

	public void setOlist(List<Ordert> olist) {
		this.olist = olist;
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	初始化查询页面g
	 * </pre>
	 * 
	 * @return
	 */
	@RequestMapping("/init")
	public String init(HttpServletRequest request) {

		try {
			List<Account> alist = accountService.findBySearch(null);
			for (Account a : alist) {
				System.out.println(a.getName());
			}

			request.setAttribute("alist", alist);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "shopping/ordert/ordertSearch";
	}

	@RequestMapping("/initEBay")
	public String initBay() {

		return "shopping/eBay/ordertSearch";
	}

	@RequestMapping("/initAmazon")
	public String initYmx() {
		return "shopping/Amazon/ordertSearch";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	分页查询
	 * </pre>
	 * 
	 * @param ordert
	 * @param page
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/exportTest")
	public void exportTest(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("octets/stream");

		String excelName = "学生信息表";
		// 转码防止乱码
		response.addHeader("Content-Disposition",
				"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
		String[] headers = new String[] { "编号", "姓名", "年龄", "性别" };
		try {
			OutputStream out = response.getOutputStream();
			exportExcel(excelName, headers, getList(), out, "yyyy-MM-dd");
			out.close();
			System.out.println("excel导出成功！");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Description: 模拟从数据库中查询出来的数据，一般是数据表中的几列
	 * @Auther: lujinyong
	 * @Date: 2013-8-22 下午2:53:58
	 */
	public List<Map<String, Object>> getList() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 100; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("number", 1000 + i);
			map.put("name", "张三" + i);
			int age = (int) (Math.random() * 100);
			do {
				age = (int) (Math.random() * 100);
			} while (age < 10 || age > 15);
			map.put("age", age);
			map.put("sex", age % 2 == 0 ? 0 : 1);// 获得随机性别
			list.add(map);
		}
		return list;
	}

	/**
	 * 
	 * @Description: 生成excel并导出到客户端（本地）
	 * @Auther: lujinyong
	 * @Date: 2013-8-22 下午3:05:49
	 */
	protected void exportExcel(String title, String[] headers, List mapList, OutputStream out, String pattern) {
		// 声明一个工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		// 设置表格默认列宽度为15个字符
		sheet.setDefaultColumnWidth(20);
		// 生成一个样式，用来设置标题样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.VIOLET.index);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成并设置另一个样式,用于设置内容样式
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 生成另一个字体
		HSSFFont font2 = workbook.createFont();
		font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		// 把字体应用到当前的样式
		style2.setFont(font2);
		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}
		for (int i = 0; i < mapList.size(); i++) {
			Map<String, Object> map = (Map<String, Object>) mapList.get(i);
			row = sheet.createRow(i + 1);
			int j = 0;
			Object value = null;
			value = map.get("number");
			if (value instanceof Integer) {
				row.createCell(j++).setCellValue(String.valueOf(value));
			}
			row.createCell(j++).setCellValue(map.get("name").toString());
			value = map.get("age");
			if (value instanceof Integer) {
				row.createCell(j++).setCellValue(String.valueOf(value));
			}
			row.createCell(j++).setCellValue("0".equals(map.get("sex").toString()) ? "女" : "男");
		}

		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/list")
	public String list(Ordert ordert, PageController<Ordert> page, HttpServletRequest request) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date = calendar.getTime();

		Date date2 = new Date();
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(date2);
		calendar2.add(Calendar.DAY_OF_MONTH, 2);
		date2 = calendar2.getTime();

		String startDate = request.getParameter("start");
		String endDate = request.getParameter("end");
		String status = request.getParameter("status");

		if (startDate == null || startDate == "") {
			startDate = df.format(date);
		}

		if (endDate == null || endDate == "") {
			endDate = df.format(date2);
		}

		request.setAttribute("startDate", startDate);
		request.setAttribute("endDate", endDate);

		Integer platformid = 3;
		Integer accountidd = 1;

		String platformname = request.getParameter("platformnn");
		System.err.println(platformname);

		if (platformname != null) {
			Platform platform = platformDao.findByName(platformname);
			platformid = platform.getId();
		}

		String accountt = request.getParameter("accountt");
		if (accountt != null) {
			Account account = accountDao.findByName(accountt);
			accountidd = account.getId();
		}

		System.err.println("platformid=" + platformid + ",accountid=" + accountidd);

		try {

			if (status == null) {

				olist = ordertService.getByDateUtil(startDate, endDate, platformid);
				System.err.println(olist.size());

			} else {
				olist = ordertService.findByStatusUtil(startDate, endDate, Integer.parseInt(status), platformid);

			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		setOlist(olist);
		page.setResult(olist);
		page.setTotalCount(olist.size());
		page.setTotalPages(olist.size() % 10 == 0 ? olist.size() / 10 : olist.size() / 10 + 1);
		request.setAttribute("page", page);
		request.setAttribute("begin", 0);
		request.setAttribute("end", 10);

		return "shopping/ordert/ordertList";
	}

	@RequestMapping("/AmazonlistTo")
	public String AmazonlistTo(Ordert ordert, PageController<Ordert> page, HttpServletRequest request) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date = calendar.getTime();

		Date date2 = new Date();
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(date2);
		calendar2.add(Calendar.DAY_OF_MONTH, 1);
		date2 = calendar2.getTime();

		String startDate = request.getParameter("start");
		String endDate = request.getParameter("end");
		String status = request.getParameter("status");

		if (startDate == null || startDate == "") {
			startDate = df.format(date);
		}

		if (endDate == null || endDate == "") {
			endDate = df.format(date2);
		}

		request.setAttribute("startDate", startDate);
		request.setAttribute("endDate", endDate);

		try {

			if (status == null) {

				olist = ordertService.getByDateUtil(startDate, endDate, 2);

			} else {
				olist = ordertService.findByStatusUtil(startDate, endDate, Integer.parseInt(status), 2);

			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		setOlist(olist);
		page.setResult(olist);
		page.setTotalCount(olist.size());
		page.setTotalPages(olist.size() % 10 == 0 ? olist.size() / 10 : olist.size() / 10 + 1);
		request.setAttribute("page", page);
		request.setAttribute("begin", 0);
		request.setAttribute("end", 10);

		return "shopping/AmazonDatabase/ordertList";
	}

	@RequestMapping("/exportExcel")
	public void exportExcel(Ordert ordert, Page<Ordert> page, HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		JSONObject json = new JSONObject();

		String plateformidstr = request.getParameter("plateformid");
		Integer plateformid = Integer.parseInt(plateformidstr);

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date = calendar.getTime();

		String startDate = request.getParameter("start");
		String endDate = request.getParameter("end");
		String status = request.getParameter("status");
		String filePath = request.getParameter("filePath");

		if (startDate == null || startDate == "") {
			startDate = df.format(date);
		}

		if (endDate == null || endDate == "") {
			endDate = df.format(new Date());
		}

		String dateBet = "成功导出" + startDate + "至" + endDate + "的订单";
		System.out.println(status == null ? "null" : status);

		String excelName = "";
		if (plateformid == 3) {
			excelName = "手工订单信息";
		}

		if (plateformid == 1) {
			excelName = "eBay订单信息";
		}

		if (plateformid == 2) {
			excelName = "亚马逊订单信息";
		}

		ExcelFileUtil excel = new ExcelFileUtil();

		response.setContentType("octets/stream");
		response.addHeader("Content-Disposition",
				"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");

		OutputStream out = response.getOutputStream();

		try {

			if (status == null) {

				List<Ordert> oList = ordertService.getByDateUtil(startDate, endDate, plateformid);
				System.err.println(oList.size());
				List<EBayInfoNeed> ebst = eBayExcel(oList, filePath, plateformid, response);

				excel.write(excelName, ebst, EBayInfoNeed.class, out);
				out.close();
				System.out.println("excel导出成功！");

			} else {

				List<Ordert> oList = ordertService.findByStatusUtil(startDate, endDate, Integer.parseInt(status),
						plateformid);
				System.err.println(oList.size());
				List<EBayInfoNeed> ebst = eBayExcel(oList, filePath, plateformid, response);

				excel.write(excelName, ebst, EBayInfoNeed.class, out);
				out.close();
				System.out.println("excel导出成功！");

			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("result", "导出失败");
		}

	}

	public List<EBayInfoNeed> eBayExcel(List<Ordert> oList, String filePath, Integer plateformid,
			HttpServletResponse response) throws IOException {

		List<EBayInfoNeed> ebst = new ArrayList<EBayInfoNeed>();

		for (Ordert o : oList) {

			EBayInfoNeed eBayInfoNeed = new EBayInfoNeed();
			eBayInfoNeed.setSaleRecordNumber("");
			eBayInfoNeed.setUserId(o.getPerson().getUid());
			eBayInfoNeed.setBuyerFullname(o.getPerson().getName());
			eBayInfoNeed.setBuyerPhoneNumber(o.getPerson().getPhone());
			eBayInfoNeed.setBuyerEmail("");
			String address = o.getPerson().getAddress();
			if (address == null || address == "") {
				System.out.println("adress is null");
			} else {
				String[] addresstr = address.split(",");
				int len = addresstr.length;
				eBayInfoNeed.setBuyerCountry(len > 0 ? addresstr[0] : "");
				eBayInfoNeed.setBuyerState(len > 1 ? addresstr[1] : "");
				eBayInfoNeed.setBuyerCity(len > 2 ? addresstr[2] : "");
				eBayInfoNeed.setBuyerAddress1(len > 3 ? addresstr[3] : "");
				eBayInfoNeed.setBuyerAddress2(len > 4 ? addresstr[4] : "");

			}
			eBayInfoNeed.setBuyerZip(o.getPerson().getZipcode());
			// 商品清单
			List<OrderItem> orderItem = ordertService.findItems(o.getId());
			eBayInfoNeed.setItemNumber(orderItem.size() + "");
			eBayInfoNeed.setItemTitle(orderItem.get(0).getProduct().getName());
			eBayInfoNeed.setCustomLabel("客户备注");
			eBayInfoNeed.setQuantity(orderItem.get(0).getCount() + "");
			eBayInfoNeed.setSalePrice(orderItem.get(0).getPrice() + "");
			eBayInfoNeed.setShippingandHandling("");
			eBayInfoNeed.setUuuSTax("");
			eBayInfoNeed.setInsurance("");
			eBayInfoNeed.setCashondeliveryfee("");
			eBayInfoNeed.setTotalPrice(orderItem.get(0).getTotalPrice() + "");
			eBayInfoNeed.setPaymentMethod("");
			eBayInfoNeed.setSaleDate("");
			eBayInfoNeed.setCheckoutDate("");
			eBayInfoNeed.setPaidonDate("");
			eBayInfoNeed.setShippedonDate("");
			eBayInfoNeed.setFeedbackleft("");
			eBayInfoNeed.setFeedbackreceived("");
			eBayInfoNeed.setNotestoyourself("");
			eBayInfoNeed.setPayPalTransactionID("");
			eBayInfoNeed.setShippingService("");
			eBayInfoNeed.setCashondeliveryoption("");
			eBayInfoNeed.setTransactionID("");
			eBayInfoNeed.setOrderID("");
			eBayInfoNeed.setVariationDetails("");
			ebst.add(eBayInfoNeed);
		}

		System.out.println(ebst.size());

		return ebst;
	}

	private static String[] ReverseTargetArray(String[] array, int index, int length) {
		// 保证起始下标和求逆元素个数的合法性
		if (index < 0 || length > array.length || index + length > array.length) {
			return null;
		}
		int first = index; // 记录求逆的起始元素位置
		int second = length + first - 1; // 记录求逆的终止元素位置
		int cutl = second - first;
		int oldl = array.length - second;

		System.out.println(cutl + "," + oldl);

		String[] cut = new String[cutl + 1];

		for (int i = 0; i < cut.length; i++) {
			cut[i] = array[i];
		}

		System.out.println(Arrays.toString(cut));

		String[] old = new String[array.length - cut.length];

		for (int i = 0; i < old.length; i++) {
			old[i] = array[i + cut.length];
		}

		System.out.println(Arrays.toString(old));

		String[] newstr = new String[12];

		for (int i = 0; i < 12; i++) {
			if (i < old.length) {
				newstr[i] = old[i];
			} else {
				newstr[i] = cut[i - old.length];
			}

		}

		System.out.println(Arrays.toString(newstr));

		return newstr;
	}

	@RequestMapping("/indexShow1")
	@ResponseBody
	public String indexShow1(HttpServletRequest request) {

		Calendar cal = Calendar.getInstance();
		int month = cal.get(Calendar.MONTH);
		String[] array = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
		array = ReverseTargetArray(array, 0, month + 1);

		JSONObject json = new JSONObject();

		int[] c = new int[12];

		for (int i = 0; i < 11; i++) {

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MONTH, -i - 1);
			date = calendar.getTime();

			Date date2 = new Date();
			Calendar calendar2 = Calendar.getInstance();
			calendar2.setTime(date2);
			calendar2.add(Calendar.MONTH, -i);
			date2 = calendar2.getTime();

			String startDate = request.getParameter("start");
			String endDate = request.getParameter("end");

			if (startDate == null || startDate == "") {
				startDate = df.format(date);
			}

			if (endDate == null || endDate == "") {
				endDate = df.format(date2);
			}

			System.err.println(startDate + "," + endDate);

			olist = ordertService.getByDateAll(startDate, endDate);

			System.out.println(olist.size());

			c[i] = olist.size();

		}

		int[] arr = reverseArry(c);

		System.out.println(Arrays.toString(arr));

		json.put("arr", arr);
		json.put("arryear", array);

		return json.toString();

	}

	@RequestMapping("/ebaychart1")
	@ResponseBody
	public String ebaychart1(HttpServletRequest request) {

		Calendar cal = Calendar.getInstance();
		int month = cal.get(Calendar.MONTH);
		String[] array = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
		array = ReverseTargetArray(array, 0, month + 1);

		JSONObject json = new JSONObject();

		int[] c = new int[12];
		int[] c1 = new int[12];
		int[] c2 = new int[12];

		for (int i = 0; i < 11; i++) {

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MONTH, -i - 1);
			date = calendar.getTime();

			Date date2 = new Date();
			Calendar calendar2 = Calendar.getInstance();
			calendar2.setTime(date2);
			calendar2.add(Calendar.MONTH, -i);
			date2 = calendar2.getTime();

			String startDate = request.getParameter("start");
			String endDate = request.getParameter("end");

			if (startDate == null || startDate == "") {
				startDate = df.format(date);
			}

			if (endDate == null || endDate == "") {
				endDate = df.format(date2);
			}

			System.err.println(startDate + "," + endDate);

			olist = ordertService.getByDateUtil(startDate, endDate, 1);

			List<Ordert> clist1 = ordertService.getByDateUtil(startDate, endDate, 2);

			List<Ordert> clist2 = ordertService.getByDateUtil(startDate, endDate, 3);

			System.out.println(olist.size());
			System.out.println(clist2.size());

			c[i] = olist.size();

			c1[i] = clist1.size();

			c2[i] = clist2.size();

		}

		int[] arr = reverseArry(c);

		int[] arr1 = reverseArry(c1);

		int[] arr2 = reverseArry(c2);

		System.out.println(Arrays.toString(arr));

		json.put("arr", arr);
		json.put("arr1", arr1);
		json.put("arr2", arr2);
		json.put("arryear", array);

		return json.toString();

	}

	@RequestMapping("/indexShow2")
	@ResponseBody
	public String indexShow2(HttpServletRequest request) {

		JSONObject json = new JSONObject();

		int[] c = new int[4];

		for (int i = 0; i < 4; i++) {

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.WEEK_OF_YEAR, -i - 1);
			date = calendar.getTime();

			Date date2 = new Date();
			Calendar calendar2 = Calendar.getInstance();
			calendar2.setTime(date2);
			calendar2.add(Calendar.WEEK_OF_YEAR, -i);
			date2 = calendar2.getTime();

			String startDate = request.getParameter("start");
			String endDate = request.getParameter("end");

			if (startDate == null || startDate == "") {
				startDate = df.format(date);
			}

			if (endDate == null || endDate == "") {
				endDate = df.format(date2);
			}

			System.err.println(startDate + "," + endDate);

			olist = ordertService.getByDateAll(startDate, endDate);

			System.out.println(olist.size());

			c[i] = olist.size();

		}

		int[] arr = reverseArry(c);

		System.out.println(Arrays.toString(arr));

		json.put("arr", arr);

		return json.toString();

	}

	public static int[] reverseArry(int[] arr) {
		for (int i = 0; i < arr.length / 2; i++) {
			int temp = arr[i];
			arr[i] = arr[arr.length - 1 - i];
			arr[arr.length - 1 - i] = temp;
		}

		return arr;
	}

	@RequestMapping("/eBayList")
	public String eBayList(Ordert ordert, PageController<Ordert> page, HttpServletRequest request) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date = calendar.getTime();

		Date date2 = new Date();
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(date2);
		calendar2.add(Calendar.DAY_OF_MONTH, 1);
		date2 = calendar2.getTime();

		String startDate = request.getParameter("start");
		String endDate = request.getParameter("end");
		String status = request.getParameter("status");

		if (startDate == null || startDate == "") {
			startDate = df.format(date);
		}

		if (endDate == null || endDate == "") {
			endDate = df.format(date2);
		}

		request.setAttribute("startDate", startDate);
		request.setAttribute("endDate", endDate);

		System.err.println("列出" + startDate + "," + endDate);
		System.out.println(status == null ? "null" : status);

		try {

			if (status == null) {

				olist = ordertService.getByDate(startDate, endDate);

			} else {
				olist = ordertService.findByStatus(startDate, endDate, Integer.parseInt(status));

			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		setOlist(olist);
		page.setResult(olist);
		page.setTotalCount(olist.size());
		page.setTotalPages(olist.size() % 10 == 0 ? olist.size() / 10 : olist.size() / 10 + 1);
		request.setAttribute("page", page);
		request.setAttribute("begin", 0);
		request.setAttribute("end", 10);
		return "shopping/eBay/ordertList";
	}

	@RequestMapping("/nextPage")
	public String nextTokenPage(PageController<Ordert> page, HttpServletRequest request) {

		String pageNo = request.getParameter("pageNo");
		int pageNo1 = Integer.parseInt(pageNo);

		int begin = (pageNo1 - 1) * 10;
		int end = begin + 10;
		page.setResult(getOlist());
		page.setPageNo(pageNo1);
		page.setTotalCount(getOlist().size());
		page.setTotalPages(getOlist().size() % 10 == 0 ? getOlist().size() / 10 : getOlist().size() / 10 + 1);
		request.setAttribute("page", page);
		request.setAttribute("begin", begin);
		request.setAttribute("end", end);

		return "shopping/eBay/ordertList";
	}

	@RequestMapping("/eBayListDate")
	public String eBayListDate(Ordert ordert, Page<Ordert> page, HttpServletRequest request) {

		String startDate = request.getParameter("start");
		String endDate = request.getParameter("end");

		try {

			request.setAttribute("pageEBayList", ordertService.getByDate(startDate, endDate));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/eBay/ordertList";
	}

	@RequestMapping("/eBayOrderDetail")
	public String eBayOrderDetail(Ordert ordert, String code, Page<Ordert> page, HttpServletRequest request) {
		try {

			Ordert o = ordertService.findByCode(code);
			List<OrderItem> orderItem = ordertService.findItems(o.getId());
			request.setAttribute("ordertDetail", o);
			request.setAttribute("orderItems", orderItem);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/ordert/handOrderDetail";
	}

	@RequestMapping("/handOrderDetail")
	public String handOrderDetail(Ordert ordert, String code, Page<Ordert> page, HttpServletRequest request) {

		try {

			Ordert o = ordertService.findByCode(code);
			List<OrderItem> orderItem = ordertService.findItems(o.getId());
			List<Platform> plist = platformService.findBySearch(null);
			DeliverGoods deliverGoods = deliverGoodsDao.findByOrderid(o.getId());

			request.setAttribute("ordertDetail", o);
			request.setAttribute("orderItems", orderItem);
			request.setAttribute("plist", plist);
			request.setAttribute("deliverGoods", deliverGoods);
			request.setAttribute("warehouses", warehouseService.findBySearch(null));
			request.setAttribute("code", code);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "shopping/ordert/handOrderDetail";

	}

	@RequestMapping("/handOrderDetailEdit")
	public String handOrderDetailEdit(Ordert ordert, String code, Page<Ordert> page, HttpServletRequest request) {

		System.err.println("handOrderDetailEdit");
		try {

			Ordert o = ordertService.findByCode(code);
			List<OrderItem> orderItem = ordertService.findItems(o.getId());
			List<Platform> plist = platformService.findBySearch(null);
			DeliverGoods deliverGoods = deliverGoodsDao.findByOrderid(o.getId());
			List<Logistics> loglist = logisticsService.findBySearch(null);
			request.setAttribute("ordertDetail", o);
			request.setAttribute("orderItems", orderItem);
			request.setAttribute("plist", plist);
			request.setAttribute("deliverGoods", deliverGoods);
			request.setAttribute("warehouses", warehouseService.findBySearch(null));
			request.setAttribute("loglist", loglist);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "shopping/ordert/OrdertEdit";

	}

	@RequestMapping("/amazonList")
	public String amazonList(Ordert ordert, Page<Ordert> page, HttpServletRequest request) {
		try {
			request.setAttribute("page", ordertService.getByPlatformId(2, page));
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}
		return "shopping/Amazon/ordertList";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	新增修改页面初始化
	 * </pre>
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/ordert")
	public String ordert(Integer id, HttpServletRequest request) {

		try {

			if (ValidateUtils.isNotEmpty(id)) {

				Ordert ordert = ordertService.getById(id);
				List<Platform> pflist = platformService.findBySearch(null);
				List<OrderStatus> stlist = orderStatusService.findBySearch(null);
				request.setAttribute("ordert", ordert);
				request.setAttribute("pflist", pflist);
				request.setAttribute("stlist", stlist);

			}
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}

		return "shopping/ordert/ordert";
	}

	@RequestMapping("/ListFormsaves")
	@ResponseBody
	public String ListFormsaves(HttpServletRequest request) {

		JSONObject json = new JSONObject();

		String orderid = request.getParameter("id");
		String createtime = request.getParameter("createtime");
		String code = request.getParameter("code");
		String uid = request.getParameter("uid");
		String count = request.getParameter("count");
		String price = request.getParameter("price");
		String description = request.getParameter("description");
		String platformId = request.getParameter("platformId");
		String orderStatusId = request.getParameter("orderStatusId");

		Ordert ordert = new Ordert();
		ordert.setId(Integer.parseInt(orderid));
		ordert.setCreatetime(createtime);
		ordert.setCode(code);
		ordert.setCount(count == null ? null : Integer.parseInt(count));
		ordert.setPrice(price == null ? null : Double.valueOf(price));
		ordert.setDescription(description);
		ordert.setPlatformId(platformId == null ? null : Integer.parseInt(platformId));
		ordert.setOrderStatusId(orderStatusId == null ? null : Integer.parseInt(orderStatusId));

		try {

			if (ValidateUtils.isNotEmpty(ordert.getId())) {

				System.out.println(ordert.getOrderStatusId());
				System.out.println(ordert.getPlatformId());

				ordertService.updateNotNull(ordert);

			}

			json.put("result", "保存成功");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "保存失败");
		}

		return json.toString();
	}

	@RequestMapping("/newHandOrderThis")
	public String newHandOrderThis(HttpServletRequest request) {

		try {

			List<Platform> plist = platformService.findBySearch(null);
			Collections.reverse(plist);
			List<Logistics> loglist = logisticsService.findBySearch(null);
			request.setAttribute("plist", plist);
			request.setAttribute("warehouses", warehouseService.findBySearch(null));
			request.setAttribute("loglist", loglist);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "shopping/ordert/handOrdert";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	保存
	 * </pre>
	 * 
	 * @param ordert
	 * @return
	 */
	@RequestMapping("/saveUpdate")
	@ResponseBody
	public String saveUpdate(HttpServletRequest request) {

		JSONObject json = new JSONObject();

		String salechannel = request.getParameter("salechannel");
		String accountname = request.getParameter("accountname");
		String orderid = request.getParameter("orderid");

		System.out.println("---------------------------orderid" + orderid);
		Ordert o = ordertService.findByCode(orderid);

		String checkpend = request.getParameter("checkpend");
		String paymethod = request.getParameter("paymethod");
		String paydate = request.getParameter("paydate");
		String totalpay = request.getParameter("totalpay");

		String receivername = request.getParameter("receivername");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String postalcode = request.getParameter("postalcode");

		String warsehose = request.getParameter("warsehose");
		String shiptype = request.getParameter("shiptype");
		String shipnumid = request.getParameter("shipnumid");

		String note = request.getParameter("note");

		String productname1 = request.getParameter("productname1");
		String sku1 = request.getParameter("sku1");
		String price1 = request.getParameter("price1");
		String amount1 = request.getParameter("amount1");
		String currentstock1 = request.getParameter("currentstock1");
		String shipsku1 = request.getParameter("shipsku1");
		String totalprice1 = request.getParameter("totalprice1");

		String productname2 = request.getParameter("productname2");
		String sku2 = request.getParameter("sku2");
		String price2 = request.getParameter("price2");
		String amount2 = request.getParameter("amount2");
		String currentstock2 = request.getParameter("currentstock2");
		String shipsku2 = request.getParameter("shipsku2");
		String totalprice2 = request.getParameter("totalprice2");

		String orderStatus = request.getParameter("orderStatusId");

		Ordert ordert = ordertService.findByCode(orderid);
		List<OrderItem> orderItems = orderItemDao.findByOrderId(ordert.getId());
		for (OrderItem os : orderItems) {
			orderItemDao.delete(os.getId());
		}

		OrderItem orderItem = new OrderItem();
		Person person = personDao.getById(ordert.getPersonId());
		Product product = new Product();
		DeliverGoods deliverGoods = deliverGoodsDao.findByOrderid(ordert.getId());

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {

			person.setId(o.getPersonId());
			person.setAddress(address);
			person.setName(receivername);
			person.setPhone(phone);
			person.setUid(accountname);
			person.setZipcode(postalcode);

			if (sku1 != null) {
				product = productDao.getByCode(sku1);
			} else {
				product = null;
				sku1 = "SKU" + df.format(new Date());
			}

			if (product == null) {
				product = new Product();
				product.setCode(sku1);
				product.setName(productname1 == null ? "null" : productname1);
				product.seteBayCode(sku1 == null ? "null" : sku1);
				product.setProductStatusId(1);
				productDao.add(product);
			} else {

				product.setCode(sku1);
				product.setName(productname1 == null ? null : productname1);
				product.seteBayCode(sku1 == null ? null : sku1);
				product.setProductStatusId(1);
				productDao.updateNotNull(product);

			}

			orderItem.setProductId(product.getId());
			orderItem.setSku(sku1);
			orderItem.setTotalPrice(totalprice1 == null ? 0 : Double.parseDouble(totalprice1));
			orderItem.setPrice(price1 == null ? 0 : Double.parseDouble(price1));
			orderItem.setCount(amount1 == null ? 0 : Integer.valueOf(amount1));

			personDao.updateNotNull(person);

			ordert.setCode(orderid);
			Integer orderstatus = Integer.parseInt(orderStatus);
			ordert.setOrderStatusId(orderstatus);
			ordert.setCreatetime(paydate);
			Integer platformid = Integer.parseInt(salechannel);
			ordert.setPlatformId(platformid);
			Integer warehoseid = Integer.parseInt(warsehose);
			ordert.setWarehouseId(warehoseid);
			ordert.setPersonId(person.getId());

			ordert.setCount(amount1 == null ? null : Integer.parseInt(amount1));
			ordert.setPrice(price1 == null ? null : Double.valueOf(price1));
			ordert.setDescription(note);

			ordertDao.updateNotNull(ordert);

			orderItem.setOrdertId(ordert.getId());
			System.out.println(orderItem);
			orderItemDao.add(orderItem);

			if (deliverGoods == null) {
				deliverGoods = new DeliverGoods();
				deliverGoods.setOrdertId(ordert.getId());
				deliverGoods.setLogisticsCode(shipnumid);
				Logistics logistics = logisticsDao.getIdByName(shiptype);
				deliverGoods.setLogisticsId(logistics.getId());
				deliverGoodsDao.add(deliverGoods);

			} else {

				deliverGoods.setOrdertId(ordert.getId());
				deliverGoods.setLogisticsCode(shipnumid);
				deliverGoods.setLogisticsId(Integer.parseInt(shiptype));
				deliverGoodsDao.updateNotNull(deliverGoods);

			}

			json.put("result", "保存成功");

		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "保存失败");
		}

		return json.toString();
	}

	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpServletRequest request) {

		JSONObject json = new JSONObject();

		String salechannel = request.getParameter("salechannel");
		String accountname = request.getParameter("accountname");
		String orderid = request.getParameter("orderid");

		String checkpend = request.getParameter("checkpend");
		String paymethod = request.getParameter("paymethod");
		String paydate = request.getParameter("paydate");
		String totalpay = request.getParameter("totalpay");

		String receivername = request.getParameter("receivername");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String postalcode = request.getParameter("postalcode");

		String warsehose = request.getParameter("warsehose");
		String shiptype = request.getParameter("shiptype");
		String shipnumid = request.getParameter("shipnumid");

		String note = request.getParameter("note");

		String productname1 = request.getParameter("productname1");
		String sku1 = request.getParameter("sku1");
		String price1 = request.getParameter("price1");
		String amount1 = request.getParameter("amount1");
		String currentstock1 = request.getParameter("currentstock1");
		String shipsku1 = request.getParameter("shipsku1");
		String totalprice1 = request.getParameter("totalprice1");

		String productname2 = request.getParameter("productname2");
		String sku2 = request.getParameter("sku2");
		String price2 = request.getParameter("price2");
		String amount2 = request.getParameter("amount2");
		String currentstock2 = request.getParameter("currentstock2");
		String shipsku2 = request.getParameter("shipsku2");
		String totalprice2 = request.getParameter("totalprice2");

		Ordert ordert = new Ordert();
		OrderItem orderItem = new OrderItem();
		Person person = new Person();
		Product product = new Product();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {

			person.setAddress(address);
			person.setName(receivername);
			person.setPhone(phone);
			person.setUid(accountname);
			person.setZipcode(postalcode);

			product = productDao.getByCode(sku1);
			if (product == null) {
				product = new Product();
				product.setCode(sku1);
				product.setName(productname1);
				product.seteBayCode(sku1);
				product.setProductStatusId(1);
				productDao.add(product);
			}
			orderItem.setProductId(product.getId());
			orderItem.setSku(sku1);
			orderItem.setTotalPrice(Double.parseDouble(totalprice1));
			orderItem.setPrice(Double.parseDouble(price1));
			orderItem.setCount(Integer.valueOf(amount1));

			personDao.add(person);

			ordert.setCode(orderid);
			Integer orderstatus = 1;
			ordert.setOrderStatusId(orderstatus);
			ordert.setCreatetime(df.format(new Date()));
			Integer platformid = Integer.parseInt(salechannel);
			ordert.setPlatformId(platformid);
			Integer warehoseid = Integer.parseInt(warsehose);
			ordert.setWarehouseId(warehoseid);
			ordert.setPersonId(person.getId());

			ordert.setCount(Integer.parseInt(amount1));
			ordert.setPrice(Double.valueOf(price1));

			ordertDao.add(ordert);

			orderItem.setOrdertId(ordert.getId());
			System.out.println(orderItem);
			orderItemDao.add(orderItem);

			DeliverGoods deliverGoods = deliverGoodsDao.findByOrderid(ordert.getId());
			if (deliverGoods == null) {
				deliverGoods = new DeliverGoods();
				deliverGoods.setOrdertId(ordert.getId());
				deliverGoods.setLogisticsCode(shipnumid);
				deliverGoods.setLogisticsId(Integer.parseInt(shiptype));
				deliverGoodsDao.add(deliverGoods);
			} else {

				deliverGoods.setOrdertId(ordert.getId());
				deliverGoods.setLogisticsCode(shipnumid);
				deliverGoods.setLogisticsId(Integer.parseInt(shiptype));
				deliverGoodsDao.updateNotNull(deliverGoods);

			}

			json.put("result", "保存成功");

		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "保存失败");
		}

		return json.toString();
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	删除
	 * </pre>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(Integer id) {

		JSONObject json = new JSONObject();

		try {

			ordertService.delete(id);
			json.put("result", "delete_success");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("result", "delete_fail");
		}

		return json.toString();
	}

	/**
	 * eBay数据同步(仅eBay数据需要使用api接口进行同步)
	 * 
	 * @param request
	 * @return
	 * @throws ApiException
	 * @throws SdkException
	 * @throws Exception
	 */
	@RequestMapping("/synchronization")
	@ResponseBody
	public String synchronization(HttpServletRequest request) throws ApiException, SdkException, Exception {
		JSONObject json = new JSONObject();
		Integer platformId = 1;
		Integer accountiddd = 1;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = ordertDao.getCreateTimeByPlatformDesc(platformId);
			Date today = new Date();
			int tongbuday = 365;
			if (date != null) {
				tongbuday = daysBetween(date, today);
			}

			String token = "";

			String accountid = request.getParameter("id");

			if (accountid != null) {

				Account account = accountService.getById(Integer.parseInt(accountid));
				token = account.getOrderApi();
				accountiddd = Integer.parseInt(accountid);
				
			}

			System.err.println("传入Token 令牌＝" + token+",accountid"+accountiddd);

			System.err.println(accountiddd);
			List<EBayInfo> infos = ReturnEBayOrder.returnOrders(tongbuday + 1, token);
			System.out.println(infos.size());

			Integer count = ordertService.synchronization(infos, platformId, accountiddd);
			if (count == 0) {
				json.put("result", "没有新的订单");
				json.put("para", 0);
				json.put("accountid", accountiddd);
			} else {
				json.put("result", "同步成功,新增" + count + "条订单");
				json.put("para", 1);
				json.put("accountid", accountiddd);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("para", 48);
			json.put("result", "同步失败");
			json.put("accountid", accountiddd);
		}
		return json.toString();
	}

	public static int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

}
